#include "blob_t.h"
#include "../libcbgl32memory/libcbgl32memory.h"
#include <assert.h>

INLINE blob_t* blob_create(blob_t* b)
{
	blob_t* rv = (blob_t*)cbgl_malloc( sizeof(blob_t) );
	rv->next = 0;
	rv->available = MAX_BDATA_PER_BLOB;

	if(b)
	{
		while(b->next)
		{
			b = b->next;
		}
		b->next = rv;
	}

	return rv;
}

INLINE void* blob_alloc(blob_t* b, size_t sz)
{
	size_t slot;

	assert(sz <= MAX_BDATA_PER_BLOB);
	assert(b);

	while( (!b->available) && b->next )
	{
		b = b->next;
	}

	if(!b->available)
	{
		b = blob_create(b);
	}

	slot = MAX_BDATA_PER_BLOB - b->available;
	b->data[slot].data = cbgl_malloc(sz);
	b->data[slot].size = sz;
	b->available--;

	return b->data[slot].data;
}

INLINE void blob_destroy(blob_t* b)
{
	blob_t* tmp;
	size_t i;

	assert(b);

	while(b)
	{
		size_t slots = MAX_BDATA_PER_BLOB - b->available;
		for(i = 0; i < slots; ++i)
		{
			cbgl_free(b->data[i].data);
		}
		tmp = b;
		b = b->next;
		cbgl_free(tmp);
	}
}